import { useEffect, useState, useRef, useMemo } from "react";
import { Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

export const UpLoader = (props) => {
    const { accept, onHandUpload, maxCount = 0, fileSize = 50, fileType = ['rar', 'zip', 'doc', 'docx', 'pdf', 'jpg'] } = props

    const propsUpload: UploadProps = {
        action: `${import.meta.env.VITE_API_URL}/uploadFile`,
        maxCount, // 限制上传文件个数
        beforeUpload: (file) => {
            // console.log('file:', file)
            const isLt = file.size / 1024 / 1024 < fileSize;
            let fileExtension = "";
            if (file.name.lastIndexOf(".") > -1) {
                fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
            }

            let isTypeOk = fileType.some((type) => {
                if (file.type.indexOf(type) > -1) return true;
                if (fileExtension && fileExtension.indexOf(type) > -1) return true;
                return false;
            })
            // console.log('isTypeOk', isTypeOk)

            // 校检文件大小
            if (!isLt) {
                message.error("文件超过50MB");
            } else if (!isTypeOk) {
                message.error(`${file.name}的文件格式不正确`);
            }
            return isLt && isTypeOk || Upload.LIST_IGNORE;

        },
        onChange({ file, fileList }) {
            if (file.status !== 'uploading') {
                // console.log(file, fileList);
                onHandUpload(file, fileList)
            }
        },
        defaultFileList: [
            //     {
            //         uid: '1',
            //         name: 'xxx.png',
            //         status: 'uploading',
            //         url: 'http://www.baidu.com/xxx.png',
            //         percent: 33,
            //     },
        ],
    };

    return (
        <Upload {...propsUpload} accept={accept}>
            <Button icon={<UploadOutlined />}>上传文件</Button>
            <div style={{ width: '500px', marginTop: '7px', color: '#606266' }}>请上传 单个文件不超过 <span style={{ color: '#f56c6c' }}>{fileSize}MB</span> 格式为 <span style={{ color: '#f56c6c' }}>{fileType.join('/')}</span> 的文件</div>
        </Upload>
    )
}

export default UpLoader
